// pages/shopCar/shopCar.js
let util = require('../../utils/util');
const api = require('../../utils/api');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [],
    startX: 0, //触摸开始的X轴位置
    delBtnWidth: 100, //删除按钮宽度单位
    flag: [],
    yuanAct: "",
    cut: false,
    number: 1,
    allPrice: 0
  },
  // 开始触发滑动
  touchS(e) {
    if (e.touches.length == 1) {
      this.setData({
        //记录触摸起始位置的X坐标
        startX: e.touches[0].clientX
      });
    }
  },
  // 触摸过程
  touchM: function (e) {
    var that = this
    if (e.touches.length == 1) {
      //记录触摸点位置的X坐标
      var moveX = e.touches[0].clientX;
      //计算手指起始点的X坐标与当前触摸点的X坐标的差值
      var disX = that.data.startX - moveX;
      //delBtnWidth 为右侧按钮区域的宽度
      var delBtnWidth = that.data.delBtnWidth;
      var delDisX = delBtnWidth - disX;
      var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变
        txtStyle = "left:0px";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "rpx";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "rpx";
        }
      }
      //获取手指触摸的是哪一个item
      var index = e.currentTarget.dataset.index;
      var list = that.data.goodsList;
      //将拼接好的样式设置到当前item中
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        goodsList: list
      });
    }
  },
  touchE: function (e) {
    var that = this;
    if (e.changedTouches.length == 1) {
      //手指移动结束后触摸点位置的X坐标
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = that.data.startX - endX;
      var delBtnWidth = that.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "rpx" : "left:0rpx";
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = that.data.goodsList;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      that.setData({
        goodsList: list
      });
    }
  },
  //删除item  
  delAddress: function (e) {
    var dataId = e.currentTarget.dataset.id;
    var goodsList = this.data.goodsList;
    let that = this;
    wx.showModal({
      title: '确认删除',
      content: '是否删除？',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: res => {
        if (res.confirm) {
          util.myRequest(
            api.cartDelete, {
              productIds: goodsList[dataId].product_id.toString()
            },
            res => {
              console.log(res.data.data);
              that.setData({
                flag: []
              })
              res.data.data.cartList.forEach((item, index) => {
                item.number = 1;
                that.setData({
                  ["flag[" + index + "]"]: 0
                })
              })
              this.setData({
                goodsList: res.data.data.cartList,
                cut: !that.data.cut
              });
              that.allcheck();
              that.getAllPrice(that.data.goodsList);
            },
            'POST'
          );
        }
      }
    });
  },
  //生命周期函数
  onShow: function (options) {
    let that = this;
    app.global.activeGoods = [];
    that.setData({
      cut: false
    })
    util.myRequest(
      api.cartIndex, {},
      res => {
        res.data.data.cartList.forEach((item, index) => {
          item.number = 1;
          that.setData({
            ["flag[" + index + "]"]: 0
          })
        })
        that.setData({
          goodsList: res.data.data.cartList,
        })
      }
    );
  },
  //点击圆圈选择商品或取消商品
  onchenk(e) {
    let that = this;
    var dataId = e.currentTarget.dataset.id;
    var goodsList = that.data.goodsList;
    var flag = that.data.flag;
    that.setData({
      ["flag[" + dataId + "]"]: !that.data.flag[dataId] ? 1 : 0
    })
    let isAll = 0;
    for (let i = 0; i < flag.length; i++) {
      if (flag[i] === 1) {
        isAll = 1;
      } else {
        isAll = 0;
        break;
      }
    }
    if (isAll === 1) {
      that.setData({
        cut: true,
        allPrice: this.getAllPrice(goodsList)
      });
    } else {
      that.setData({
        cut: false,
        allPrice: this.getAllPrice(goodsList)
      })
    }

  },
  //全选点击
  allcheck() {
    let that = this;
    var goodsList = this.data.goodsList;
    that.setData({
      cut: !that.data.cut
    })
    goodsList.forEach(function (item, index) {
      if (that.data.cut) {
        that.setData({
          ["flag[" + index + "]"]: 1,
        })
      } else {
        that.setData({
          ["flag[" + index + "]"]: 0,
        });
      }
    })
    that.setData({
      allPrice: this.getAllPrice(goodsList)
    })
    // console.log(that.data.flag)
  },
  //商品数量增加
  add(e) {

    let that = this;
    let addPid = e.currentTarget.dataset.pid;
    let goodsList = that.data.goodsList;
    let number = goodsList[addPid].number;

    that.setData({
      ['goodsList[' + addPid + '].number']: ++number,
    });
    // 计算总价
    that.setData({
      allPrice: this.getAllPrice(goodsList)
    })
    // 更新商品
    this.pushGoodsList(goodsList[addPid]);
  },
  //商品数量减少
  decrease(e) {
    let
      that = this,
      decreaseId = e.currentTarget.dataset.bid,
      goodsList = that.data.goodsList,
      number = goodsList[decreaseId].number;;

    if (number >= 2) {
      that.setData({
        ['goodsList[' + decreaseId + '].number']: --number
      })
    }
    // 计算总价
    that.setData({
      allPrice: this.getAllPrice(goodsList)
    })
    // 更新商品
    this.pushGoodsList(goodsList[decreaseId]);
  },
  //结算
  jiesuan() {
    let that = this;
    let goodsList = that.data.goodsList;
    let
      len = 0,
      productIdList = [];
    goodsList.forEach(function (item, index) {
      if (that.data.flag[index] == 1) {
        // 将所有选中的商品存到本地缓存中,
        let temGoodsArr = [];
        // 更新本地缓存
        if (wx.getStorageSync('order')) {
          temGoodsArr = wx.getStorageSync('order');
        }
        // 去重,并将重复商品的数量合并
        let
          temOrderIdArr = [],
          isOnly = true;
        // 去重
        if (temGoodsArr) {
          temGoodsArr = temGoodsArr.filter(element => {
            if (temOrderIdArr.indexOf(element.id) == -1) {
              temOrderIdArr.push(element.id);
              return true;
            }
          })
        }
        // 更新
        for (let i = 0; i < temGoodsArr.length; i++) {
          if (temGoodsArr[i].id === item.id) {
            isOnly = false;
            console.log(isOnly);
            temGoodsArr[i].number += item.number;
            break;
          }
        }
        if (isOnly) {
          console.log(isOnly);
          temGoodsArr.push(item);
        }

        wx.setStorageSync('order', temGoodsArr);
        app.global.activeGoods.push(item);
        app.global.allOrderGoods.push(item);
        productIdList.push(item.product_id);
      }
    })
    let proIdStr = productIdList.join(',');
    //选择或取消选择商品
    util.myRequest(api.cartChecked, {
        productIds: proIdStr,
        isChecked: 1
      },
      res => {
        // let goodsList = res.data.data.cartList;
        // app.global.activeGoods = 
        // app.global.activeGoods = res.data.data.cartList;

        // console.log(app.global.activeGoods);
        if (res.data.errmsg == '删除出错') {
          wx.showToast({
            title: '请选择商品',
            icon: "none"
          })
        } else {
          wx.navigateTo({
            url: '/pages/confirmation/confirmation'
          })
        }
      },
      'post'
    )

  },
  // 动态计算总价
  getAllPrice(goodsList) {
    let count = 0;
    goodsList = goodsList.filter((item, index) => {
      return this.data.flag[index] === 1;
    })
    goodsList.forEach((item, index) => {
      count += item.number * item.retail_price;
    })
    return count;
  },
  // 更新购物车商品
  pushGoodsList(goods) {
    util.myRequest(
      api.cartUpdate, {
        id: goods.id,
        goodsId: goods.goods_id,
        number: goods.number,
        productId: goods.product_id,
      },
      res => {

      },
      'POST'
    )

  }
})